package com.example.coffeeseller_2.views;

import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.example.coffeeseller_2.R;
import com.example.coffeeseller_2.model.beans.ChooseCoffeeInfo;
import com.example.coffeeseller_2.model.beans.MachineConfig;
import com.example.coffeeseller_2.model.communicate.TaskService;
import com.example.coffeeseller_2.model.contentprovider.ApplicationConstance;
import com.example.coffeeseller_2.model.databases.DealOrderInfoManager;
import com.example.coffeeseller_2.model.factory.FragmentEnum;
import com.example.coffeeseller_2.model.factory.FragmentFactory;
import com.example.coffeeseller_2.model.helper.CheckCurMachineState;
import com.example.coffeeseller_2.model.listenner.OnIsCanMakingListener;
import com.example.coffeeseller_2.model.listenner.TaskServiceListener;
import com.example.coffeeseller_2.model.parse.PayResult;
import com.example.coffeeseller_2.model.presenter.AddFragmentPresenter;
import com.example.coffeeseller_2.utils.LogFileOperator;
import com.example.coffeeseller_2.utils.MyLog;
import com.example.coffeeseller_2.utils.SingleTTs;
import com.example.coffeeseller_2.views.fragments.BasicFragment;
import com.example.coffeeseller_2.views.fragments.ChooseCupFragment;
import com.example.coffeeseller_2.views.fragments.TasteAndPayFragment;
import com.example.coffeeseller_2.views.viewinterface.IAddFragmentView;
import com.example.coffeeseller_2.widget.MyBeiSaiErView;

import cof.ac.inter.CoffMsger;
import cof.ac.inter.MachineState;
import cof.ac.inter.StateListener;

import static com.example.coffeeseller_2.model.factory.FragmentEnum.ChooseCupNumFragment;
import static com.example.coffeeseller_2.model.factory.FragmentEnum.QubeimaTasteFragment;
import static com.example.coffeeseller_2.model.factory.FragmentEnum.WelcomeFragment;

/**
 * Created by Administrator on 2018/3/20.
 */

public class HomeActivity extends AppCompatActivity implements IAddFragmentView, TaskServiceListener, StateListener {
    private static HomeActivity mInstance;
    private AddFragmentPresenter mAddFragmentPresenter;
    private TasteAndPayFragment mTasteAndPayFragment = null;
    private FrameLayout mFragContainer;
    private LinearLayout mTasteContainer;
//    private MyBeiSaiErView myBeiSaiErView;
    private LinearLayout mFooter;

    private LinearLayout mContainer;
    private String TAG = "HomeActivity";
//    private Context mContext;
    public static String Version;
    private int lastState = 0;
    private Handler handler;
    private OnIsCanMakingListener mOnIsCanMakingListener;
    private SingleTTs ts;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_home);
        init();
        handler = new Handler();
        //动态注册，此广播只能动态注册才能接收到
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);//网络的连接（包括wifi和移动网络）
        checkNetWorkType();
        DealOrderInfoManager.getInstance(this);
        CheckCurMachineState.getInstance();
        TaskService.getInstance();
        // hideNav();

      //  BlockCanary.install(this, new BlockCanaryContext()).start();
    }

    public void setOnIsCanMakingListener(OnIsCanMakingListener mOnIsCanMakingListener) {
        if (mOnIsCanMakingListener != null) {
            this.mOnIsCanMakingListener = mOnIsCanMakingListener;
        }

    }

    //全屏显示
    public void setHideVirtualKey(Window window) {
        //保持布局状态
        int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                //布局位于状态栏下方
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                //全屏
                View.SYSTEM_UI_FLAG_FULLSCREEN;
              /*  //隐藏导航栏
                 | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;*/
        if (Build.VERSION.SDK_INT >= 19) {
            uiOptions |= 0x00001000;
        } else {
            uiOptions |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
        }
        window.getDecorView().setSystemUiVisibility(uiOptions);
    }

    public boolean checkNetWorkType() {
        ConnectivityManager mConnectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        TelephonyManager mTelephony = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
//检查网络连接
        NetworkInfo info = mConnectivity.getActiveNetworkInfo();

        if (info == null || !mConnectivity.getBackgroundDataSetting()) {
            MachineConfig.setNetworkType(0);
            return false;
        }
        int netType = info.getType();
        int netSubtype = info.getSubtype();
        if (netType == ConnectivityManager.TYPE_WIFI) {  //WIFI
            Log.d(TAG, "wifi is access");
            MachineConfig.setNetworkType(2);
            return info.isConnected();
        } else if (netType == ConnectivityManager.TYPE_MOBILE && netSubtype == TelephonyManager.NETWORK_TYPE_UMTS && !mTelephony.isNetworkRoaming()) {   //MOBILE
            Log.d(TAG, "MOBILE is access");
            MachineConfig.setNetworkType(1);
            return info.isConnected();
        } else {
            Log.d(TAG, "netWorkType is unaccess");
            MachineConfig.setNetworkType(0);
            return false;
        }
    }

    public String getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static synchronized HomeActivity getInstance() {
        return mInstance;
    }

    private void init() {
        initViews();
        initDatas();

    }

    private void initDatas() {
//        mContext = this;
        Version = getVersion();
        LogFileOperator.getInstance(this);
        ApplicationConstance.getInstance();
        ApplicationConstance.getInstance().setLastClearMachineTime(System.currentTimeMillis());
        ts = SingleTTs.getSingleTTs();
        ts.init(this);

        /*
        * 解决由显示到隐藏，系统设置悬浮按钮崩溃问题
        * */
        if (CoffMsger.getInstance() != null) {
            CoffMsger.getInstance().setStateListener(this);
        }
        if (CoffMsger.getInstance() != null && CoffMsger.getInstance().getLastMachineState() != null) {

            if (!CoffMsger.getInstance().isAvailable()) {
                CoffMsger.getInstance().initDevice();
                CoffMsger.getInstance().startCheckState();
            }
        } else {
            CoffMsger.getInstance().initDevice();
            CoffMsger.getInstance().startCheckState();
        }

    }

    private void initViews() {
        mContainer = (LinearLayout) findViewById(R.id.container);
        mFragContainer = (FrameLayout) findViewById(R.id.frag_container);
        mTasteContainer = (LinearLayout) findViewById(R.id.taste_container);
        MyBeiSaiErView myBeiSaiErView = (MyBeiSaiErView) findViewById(R.id.myBeiSaiErView);
        mFooter = (LinearLayout) findViewById(R.id.footer);
        mTasteContainer.setVisibility(View.GONE);
        mFooter.setVisibility(View.GONE);
        mInstance = this;
        // FragmentFactory.curPage = MachineCheckFragment;
        FragmentFactory.curPage = WelcomeFragment;
        CoffMsger.getInstance().setStateListener(this);
        //    FragmentFactory.curPage = ChooseCupNumFragment;
        mAddFragmentPresenter = new AddFragmentPresenter(this);
        mAddFragmentPresenter.AddFragment();


        //测试用
/*        mTasteAndPayFragment = (TasteAndPayFragment) FragmentFactory.getInstance().getFragment(TasteAndPayFragment);
        mAddFragmentPresenter.AddFragment(mTasteAndPayFragment, R.id.taste_container);*/

    }


    public void replaceFragment(FragmentEnum currentPage, FragmentEnum toPage) {


        FragmentFactory.lastPage = currentPage;
        FragmentFactory.curPage = toPage;
        mAddFragmentPresenter.AddFragment();
        mFragContainer.setVisibility(View.VISIBLE);
        mContainer.setVisibility(View.VISIBLE);
        mTasteContainer.setVisibility(View.GONE);

        /*
        * 保证选杯界面每次都是重新加载的
        * */
        if (currentPage == ChooseCupNumFragment && toPage != ChooseCupNumFragment) {
            FragmentFactory.getInstance().removeFromFragment(ChooseCupNumFragment);
        }

        if (toPage == ChooseCupNumFragment || toPage == QubeimaTasteFragment) {
            mTasteAndPayFragment = (TasteAndPayFragment) FragmentFactory.getInstance().getFragment(FragmentEnum.TasteAndPayFragment);
            mAddFragmentPresenter.AddFragment(mTasteAndPayFragment, R.id.taste_container);
            mTasteContainer.setVisibility(View.VISIBLE);
            //  mFooter.setVisibility(View.VISIBLE);
        } else {

            //  mFooter.setVisibility(View.GONE);
            if (mAddFragmentPresenter != null) {
                mAddFragmentPresenter.removeFragment(mTasteAndPayFragment);
                mTasteAndPayFragment = null;
            }
            mTasteContainer.setVisibility(View.GONE);
        }
    }

    public void showFooter(boolean isShow) {
        if (isShow) {
            mFooter.setVisibility(View.VISIBLE);
        } else {
            mFooter.setVisibility(View.GONE);
        }

    }


    public void addTastPayFrag(final ChooseCoffeeInfo coffeeInfo) {

        handler.post(new Runnable() {
            @Override
            public void run() {
                if (mTasteAndPayFragment != null
                        && (FragmentFactory.curPage == ChooseCupNumFragment
                        || FragmentFactory.curPage == QubeimaTasteFragment)) {
                    mTasteAndPayFragment.setData(coffeeInfo);
                }
                mTasteContainer.setVisibility(View.VISIBLE);
            }
        });

    }

    /*
    * 显示选择口味界面
    * */
    public void showTastPayFrag() {

        MyLog.d(TAG, "mTasteAndPayFragment= " + mTasteAndPayFragment);
        if (mTasteAndPayFragment != null
                && (FragmentFactory.curPage == ChooseCupNumFragment
                || FragmentFactory.curPage == QubeimaTasteFragment)) {

            mTasteContainer.setVisibility(View.VISIBLE);
            mTasteAndPayFragment.enterAnim();
            mFragContainer.setVisibility(View.GONE);
            mContainer.setVisibility(View.GONE);

            ChooseCupFragment chooseCupFragment = (ChooseCupFragment) FragmentFactory.getInstance().getFragment(ChooseCupNumFragment);

            if (chooseCupFragment != null) {
                chooseCupFragment.setRecyclerViewVisiable(false);
                chooseCupFragment.setWaveOpen(true);
            }
        }
    }

    /*
    * 口味界面返回选杯界面
    * */
    public void backToChooseFrag(final boolean hasMake) {

        ApplicationConstance.getInstance().setPayed(false);
        ApplicationConstance.getInstance().setHasCoffeeSelected(false);
        handler.post(new Runnable() {
            @Override
            public void run() {

                if (FragmentFactory.curPage == ChooseCupNumFragment) {
                  /*
                    mFragContainer.setVisibility(View.VISIBLE);
                    mTasteContainer.setVisibility(View.GONE);
                    if (mTasteAndPayFragment != null) {
                        mTasteAndPayFragment.clear();
                        //  mTasteContainer.setVisibility(View.VISIBLE);
                    }*/

                  /*
                  * 不做选杯界面的缓存
                  * */
                    ChooseCupFragment chooseCupFragment = (ChooseCupFragment) FragmentFactory.getInstance().getFragment(ChooseCupNumFragment);
                    if (chooseCupFragment != null) {
                        chooseCupFragment.setRecyclerViewVisiable(true);
                        chooseCupFragment.setWaveOpen(false);
                    }
                } else if (FragmentFactory.curPage == QubeimaTasteFragment) {//有点延时

                    replaceFragment(FragmentFactory.curPage, ChooseCupNumFragment);
                }

                mFragContainer.setVisibility(View.VISIBLE);
                mContainer.setVisibility(View.VISIBLE);
                mTasteContainer.setVisibility(View.GONE);
                if (mTasteAndPayFragment != null) {
                    mTasteAndPayFragment.clear();
                }
            }
        });

    }

    /*
    * 更新咖啡列表
    * */
    public void updateCoffee() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (FragmentFactory.curPage == ChooseCupNumFragment) {
                    ChooseCupFragment chooseCupFragment = (ChooseCupFragment) FragmentFactory.getInstance().getFragment(ChooseCupNumFragment);
                    if (chooseCupFragment != null) {
                        chooseCupFragment.update();
                    }
                }
            }
        });

    }


    @Override
    public AppCompatActivity getActivity() {
        return this;
    }

    @Override
    public BasicFragment getFragment() {
        return FragmentFactory.getInstance().getFragment(FragmentFactory.curPage);
    }


    @Override
    public int getLayoutId() {
        return R.id.frag_container;
    }

    @Override
    public void payListenner(PayResult payResult) {

    }

    @Override
    public void formulaUpdate(String formulaId) {

    }

    /*
    * 修改清洗记录
    * */


    private boolean isCheckShiftNotRightPlace = false;//杯架在初始位置
    private long firstCheckShiftNotRightPlace;
    private boolean isSelling;

    @Override
    public void stateArrived(final MachineState machineState) {

        if (machineState != null) {
//            Log.e(TAG, "lastState is " + lastState + "current state is " + machineState.getMajorState().getStateCode() + "and crrent lowErro_byte is " + machineState.getMajorState().getHighErr_byte());
            Log.e(TAG, "lastState is " + lastState + "current state is " + machineState.getMajorState().getHighErr_byte());
            int currentState = machineState.getMajorState().getHighErr_byte();//machineState.getMajorState().getStateCode();
            if (lastState != currentState) { //上一次不等于当前的状态则提交
                TaskService.getInstance().sendStateMsg();
                lastState = currentState;
            }

/*
            boolean isShelfRightPlace = true;
            if (!machineState.isCupShelfRightPlace() && !isCheckShiftNotRightPlace) {
                firstCheckShiftNotRightPlace = System.currentTimeMillis();
                isCheckShiftNotRightPlace = true;
                Log.d(TAG, "firstCheckShiftNotRightPlace = " + firstCheckShiftNotRightPlace);

            } else if (machineState.isCupShelfRightPlace()) {
                isCheckShiftNotRightPlace = false;
            }

            Log.d(TAG, "isCheckShiftNotRightPlace = " + isCheckShiftNotRightPlace);
            if (System.currentTimeMillis() - firstCheckShiftNotRightPlace > 30 * 1000 && isCheckShiftNotRightPlace) {
                isShelfRightPlace = false;
            }

            Log.d(TAG, "isShelfRightPlace = " + isShelfRightPlace);

            boolean isStopToSell = !(CheckCurMachineState.getInstance().isCanMaking(machineState)
                    && isShelfRightPlace);


            if (mOnIsCanMakingListener != null) {
                mOnIsCanMakingListener.StateArrived(CheckCurMachineState.getInstance().isCanMaking(machineState)
                                && isShelfRightPlace,
                        machineState.getMajorState().getHighErr_byte()
                                + (isShelfRightPlace ? "" : " | 杯架故障")
                                + (!machineState.isFrontDoorOpen() ? "" : " | 机器维护中"));//)
            }*/
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.exit(0);
    }
}
